import router, { whiteList } from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条 style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { showMessage } from '@/utils/request-tools'
import { operationLog, stayLog } from '@/api/common'
// import { format } from 'crypto-js'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login'] // no redirect whitelist

const initialRouters = router.options.routes

let oldStayTimetamp = new Date().getTime()

router.beforeEach(async(to, from, next) => {
  // start 进度条
  NProgress.start()

  // 设置页面title
  document.title = getPageTitle(to.meta.title)

  // if (to.path === '/tenant') {
  //   next('/404')
  //   return
  // }
  // console.log(to, initialRouters)

  // 确定用户是否已登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.userId

      /* ---------  日志数据收集 --- start ---------- */
      const fromTitle = from.meta.localTitle
      const toTitle = to.meta.localTitle

      const newStayTimetamp = new Date().getTime()
      if (from.path !== '/login' && fromTitle) {
        // 操作记录 - 退出
        operationLog({
          event: 'out',
          resource: fromTitle,
          summary: `退出${fromTitle}页面` 
        })
        // 记录页面停留时间
        stayLog({
          resource: fromTitle,
          stayTime: Math.floor((newStayTimetamp - oldStayTimetamp) / 1000) 
        })
      }

      // 操作记录 - 进入
      if (toTitle) {
        operationLog({
          event: 'in',
          resource: toTitle,
          summary: `进入${toTitle}页面`
        })
      }

      oldStayTimetamp = newStayTimetamp
      /* ---------  日志数据收集 --- end ---------- */

      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // 获取用户信息
          await store.dispatch('user/getInfo')
          const menuMap = await store.dispatch('getMenuTree')
          await store.dispatch('GenerateRoutes', menuMap)
          const addRoutesList = store.getters.addRouters
          router.options.routes = [...initialRouters, ...addRoutesList]

          router.addRoutes(addRoutesList) // 动态添加可访问路由表

          // hack方法 确保addRoutes已完成 ,设置replace: true，这样导航就不会留下历史记录
          next({ ...to, replace: true })
        } catch (error) {
          showMessage(error)
          // 删除令牌，进入登录页面重新登录
          await store.dispatch('user/resetToken')
          // next(`/login?redirect=${to.path}`)
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 免登陆白名单
      next()
    } else {
      // 没有访问权限的其他页面被重定向到登录页面.
      // next(`/login?redirect=${to.path}`)
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish 进度条
  NProgress.done()
})
